package com.wangfei.test;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.ConcurrentHashMap;

public class JmxRemote {
    public static void main(String[] args) throws Exception {
        //Jmx地址
        String serviceURL = "service:jmx:rmi://0.0.0.0/jndi/rmi://0.0.0.0:10099/BSPConnector";
        JMXServiceURL jmxServiceURL = new JMXServiceURL(serviceURL);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL, null);
        //访问Jmx服务
        MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
        //获取内存
//        MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy
//            (mBeanServerConnection, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
//        System.out.println(memoryMXBean.getHeapMemoryUsage());

        //获取线程信息
        ThreadMXBean threadMXBean = ManagementFactory.newPlatformMXBeanProxy(
                                                                             mBeanServerConnection,
                                                                             ManagementFactory.THREAD_MXBEAN_NAME,
                                                                             ThreadMXBean.class
                                                                             );
        //long[] ids = threadMXBean.getAllThreadIds();
        //for(int i=0; i< ids.length; i++) {
        //    ThreadInfo info = threadMXBean.getThreadInfo(ids[i]);
        //    System.out.println(info.getThreadName() + " : waitedcount(" + info.getWaitedCount() + ")");
        //}
        StringBuilder sb = new StringBuilder();
        String threadName = null;
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
        long[] ids = threadMXBean.getAllThreadIds();
        for(int i=0; i< ids.length; i++) {
            ThreadInfo info = threadMXBean.getThreadInfo(ids[i]);
            String tmp = info.getThreadName() + " : waitedcount(" + info.getWaitedCount() + ")\n";
            sb.append(tmp);
            threadName = info.getThreadName();
            if (threadName.contains("Zhyyh")) {
                threadName = threadName.substring(0, threadName.lastIndexOf("-"));
                if (!map.containsKey(threadName)) {
                    map.put(threadName, 0);
                }
                map.put(threadName, map.get(threadName)+1);
            }
        }
        System.out.println(sb.toString());
        System.out.println(map);
    }
}
